"""
-------------------------------
- File_Name: transactionDepend.py
- Date: 2025/2/28
- Author: yangzhide
- Email: xxzjyzd@126.com
- Description: 数据库连接，
-------------------------------
"""
from typing import Dict

from fastapi import HTTPException
from contextlib import asynccontextmanager

from tortoise.transactions import in_transaction

from app.database.config import ORACLE_DB_CONFIG
from app.database.oracleDBPool import OracleDBPool
from app.logging.config import log
from config import get_api_environment_var

api_environment = get_api_environment_var()


@asynccontextmanager
async def _transaction_context():
    """内部事务上下文管理器"""
    async with in_transaction(connection_name=f"{api_environment.database}") as transaction:
        try:
            yield transaction
        except Exception as e:
            await transaction.rollback()
            raise e
        else:
            await transaction.commit()

async def get_transaction():
    """供 FastAPI 使用的依赖项"""
    async with _transaction_context() as transaction:
        yield transaction

# 数据库连接池实例
db_pools_instance: Dict[str, OracleDBPool] = {}

@asynccontextmanager
async def db_pools():
    """
    使用生命周期钩子启动时执行
    与系统数据库orm执行不一致
    """
    try:
        db_pools_instance[api_environment.other_oralce_01] = OracleDBPool(ORACLE_DB_CONFIG[api_environment.other_oralce_01],
                                                                 f'{api_environment.other_oralce_01}_pool')
        # 如果有其他连接池，也在这里初始化
        db_pools_instance[api_environment.other_oralce_02] = OracleDBPool(ORACLE_DB_CONFIG[api_environment.other_oralce_02],
                                                                 f'{api_environment.other_oralce_02}_pool')
        log.info("数据库连接池初始化完成。")
    except Exception as e:
        log.info(f"数据库连接池初始化失败: {e}")
        # 根据需要决定是否让应用启动失败
        raise e
    yield
    for pool_name, pool_instance in db_pools_instance.items():
        if pool_instance:
            log.info(f"关闭连接池: {pool_name}")
            pool_instance.close_pool()


def get_db_pool(db_name):
    """
    :param db_name: 数据库名称
    :return: 返回改数据库连接
    """
    def _get_pool() -> OracleDBPool:
        pool = db_pools_instance.get(db_name)
        if not pool:
            # 使用 HTTPException 让 FastAPI 返回一个标准的错误响应
            log.error(f"数据库连接池 '{db_name}' 未初始化或不可用。")
            raise HTTPException(
                status_code=503, # Service Unavailable
                detail=f"数据库连接池 '{db_name}' 未初始化或不可用。"
            )
        return pool
    return _get_pool